package com.chery.media.ui.setting.wlan

import android.os.Bundle
import com.blankj.utilcode.util.Utils
import com.chery.media.R
import com.chery.media.databinding.FragmentWlanBinding
import com.chery.media.library.base.BaseVMFragment
import com.chery.media.library.extend.gone
import com.chery.media.library.extend.setNbOnItemClickListener
import com.chery.media.library.extend.visible
import com.chery.media.library.extend.visibleOrGone
import com.chery.media.library.wlan.WifiManager
import com.chery.media.ui.dialog.PasswordDialog

class WlanFragment: BaseVMFragment<WlanViewModel, FragmentWlanBinding>() {

    private val wlanAdapter by lazy {
        WlanAdapter().apply {
            setNbOnItemClickListener { adapter, view, position ->
                val item = getItem(position)
                if(item.isEncrypt) {
                    PasswordDialog{
                        viewModel.connectWlan(item, it)
                    }.show(childFragmentManager, "password")
                }
            }
        }
    }

    override val layoutId: Int
        get() = R.layout.fragment_wlan

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        clickListener()
        mBinding.wlanList.adapter = wlanAdapter
        mBinding.wlanSwitch.toggleSwitch(WifiManager.create(Utils.getApp()).isOpened)
        mBinding.wifiLayout.visibleOrGone(mBinding.wlanSwitch.isOpened)
    }

    override fun initObserve() {
        viewModel.currentWifi.observe(this) {
            if (it != null && it.SSID().isNullOrEmpty().not()) {
                mBinding.connectTip.visible()
                mBinding.connectWlanName.visible()
                mBinding.connectWlanName.text = it.name()
            } else {
                mBinding.connectTip.gone()
                mBinding.connectWlanName.gone()
            }
        }
        viewModel.wlans.observe(this) {
            wlanAdapter.setList(it)
        }
    }

    private fun clickListener(){
        mBinding.wlanSwitch.setOnClickListener {
            if (mBinding.wlanSwitch.isOpened) {
                viewModel.openWlan()
            } else  {
                viewModel.closeWlan()
            }
            mBinding.wifiLayout.visibleOrGone(mBinding.wlanSwitch.isOpened)
        }
    }

    companion object {
        fun newInstance() = WlanFragment()
    }

}